﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using RingSong.ViewModels;
using Coding4Fun.Phone.Controls;
using System.Windows.Media.Imaging;
using System.IO;

namespace RingSong
{
    public class Com
    {
        public static IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;

        //查询子项 用法：FindChildOfType<ScrollViewer>(listbox)
        public static T FindChildOfType<T>(DependencyObject root) where T : class
        {
            var queue = new Queue<DependencyObject>();
            queue.Enqueue(root);
            while (queue.Count > 0)
            {
                DependencyObject current = queue.Dequeue();
                for (int i = VisualTreeHelper.GetChildrenCount(current) - 1; 0 <= i; i--)
                {
                    var child = VisualTreeHelper.GetChild(current, i);
                    var typedChild = child as T;
                    if (typedChild != null)
                    {
                        return typedChild;
                    }
                    queue.Enqueue(child);
                }
            }
            return null;
        }

        //设置
        public static object GetSetting(string key)
        {
            if (settings.Contains(key))
                return settings[key];
            else
                return null;
        }

        //获取设置
        public static void SetSetting(string key, object value)
        {
            if (settings.Contains(key))
                settings[key] = value;
            else
                settings.Add(key, value);
            settings.Save();
        }

        //十六进制颜色转Color对象
        public static Color HtmlToColor(string htmlColr)
        {
            int baseIndex = 1;
            byte a, r, g, b;
            a = r = g = b = 255;
            if (htmlColr.Length == 9)
            {
                a = Convert.ToByte(htmlColr.Substring(baseIndex, 2), 16);
                baseIndex += 2;
            }
            r = Convert.ToByte(htmlColr.Substring(baseIndex, 2), 16);
            g = Convert.ToByte(htmlColr.Substring(baseIndex += 2, 2), 16);
            b = Convert.ToByte(htmlColr.Substring(baseIndex += 2, 2), 16);
            return Color.FromArgb(a, r, g, b);
        }

        public static string XMLstr(string str)
        {
            return str.Replace("&amp;", "&")
                      .Replace("&lt;", "<")
                      .Replace("&gt;", ">")
                      .Replace("&quot;", "\"")
                      .Replace("&nbsp;", " ");
        }

        //修改数据，如果没有则插入一个
        public static void UpdateDict(RingViewModel r)
        {
            Dictionary<string, RingViewModel> dict = Com.GetSetting("down") as Dictionary<string, RingViewModel>;
            if (dict == null) dict = new Dictionary<string, RingViewModel>();
            dict[r.Infoid] = r;
            Com.SetSetting("down", dict);
        }

        //查找子项
        public static T FindFirstElementInVisualTree<T>(DependencyObject parentElement) where T : DependencyObject
        {
            var count = VisualTreeHelper.GetChildrenCount(parentElement);
            if (count == 0)
                return null;
            for (int i = 0; i < count; i++)
            {
                var child = VisualTreeHelper.GetChild(parentElement, i);
                if (child != null && child is T)
                {
                    return (T)child;
                }
                else
                {
                    var result = FindFirstElementInVisualTree<T>(child);
                    if (result != null)
                        return result;
                }
            }
            return null;
        }

        //通过Name查找子项
        public static T GetChildObject<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject child = null;
            T grandChild = null;

            for (int i = 0; i <= VisualTreeHelper.GetChildrenCount(obj) - 1; i++)
            {
                child = VisualTreeHelper.GetChild(obj, i);

                if (child is T && (((T)child).Name == name | string.IsNullOrEmpty(name)))
                {
                    return (T)child;
                }
                else
                {
                    grandChild = GetChildObject<T>(child, name);
                    if (grandChild != null)
                        return grandChild;
                }
            }
            return null;
        }

        //查找父控件
        public static  T GetParentObject<T>(DependencyObject obj, string name) where T : FrameworkElement
        {
            DependencyObject parent = VisualTreeHelper.GetParent(obj);

            while (parent != null)
            {
                if (parent is T && (((T)parent).Name == name | string.IsNullOrEmpty(name)))
                {
                    return (T)parent;
                }
                parent = VisualTreeHelper.GetParent(parent);
            }

            return null;
        }

        //提示消息
        public static void Msg(string str)
        {
            ToastPrompt toast = new ToastPrompt(); //实例化 
            toast.Title = "提示"; //设置标题 
            toast.Message = str; //设置正文消息 
            toast.FontSize = 15; //设置文本大小(可选) 
            toast.TextOrientation = Orientation.Vertical; //设置呈现为纵向 
            toast.Background = new SolidColorBrush(Colors.Red); //背景色(可选) 
            toast.Foreground = new SolidColorBrush(Colors.White); //前景色(可选)
            toast.Show();
            toast.Tap += (_, __) => { MainPage.panorama.DefaultItem = MainPage.panorama.Items[3]; };
        }

        //警告提示消息
        public static void WarnMsg(string str, object o)
        {
            ToastPrompt toast = new ToastPrompt(); //实例化 
            toast.Title = "提示"; //设置标题 
            toast.Message = str; //设置正文消息 
            toast.FontSize = 15; //设置文本大小(可选) 
            toast.TextOrientation = Orientation.Vertical; //设置呈现为纵向 
            toast.Background = new SolidColorBrush(Colors.Gray); //背景色(可选) 
            toast.Foreground = new SolidColorBrush(Colors.Black); //前景色(可选)
            toast.Show();
            toast.Tap += (_, __) => {
                MainPage.panorama.DefaultItem = MainPage.panorama.Items[3];
                RingViewModel r = o as RingViewModel;
                foreach (RingViewModel rr in MainPage.lst.Items)
                {
                    if (r.Infoid == rr.Infoid)
                    {
                        MainPage.lst.ScrollIntoView(rr);
                        MainPage.lst.SelectedItem = rr;
                    }
                }
            };
        }

        //成功消息
        public static void SuccMsg(string str)
        {
            ToastPrompt toast = new ToastPrompt(); //实例化 
            toast.Title = "提示"; //设置标题 
            toast.Message = str; //设置正文消息 
            toast.FontSize = 15; //设置文本大小(可选) 
            toast.TextOrientation = Orientation.Vertical; //设置呈现为纵向 
            toast.Background = new SolidColorBrush(Colors.Green); //背景色(可选) 
            toast.Foreground = new SolidColorBrush(Colors.White); //前景色(可选)
            toast.Show();
        }

        public static void playSong(MediaElement me,string path)
        {
            if (me.CurrentState == MediaElementState.Playing)
                me.Stop();
            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(path, FileMode.Open, FileAccess.Read))
                {
                    me.SetSource(fileStream);
                    me.Play();
                }
            }
        }

        public static void CheckPath()
        {
            using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!isf.DirectoryExists("/shared")) isf.CreateDirectory("/shared");
                if (!isf.DirectoryExists("/shared/transfers")) isf.CreateDirectory("/shared/transfers");
            }
        }

        public static void SetBtnContent(object o)
        {
            ListBoxItem item = MainPage.lst.ItemContainerGenerator.ContainerFromItem(o) as ListBoxItem;
            if (item == null) return;
            StackPanel pan = Com.FindFirstElementInVisualTree<StackPanel>(item);
            Grid grd = Com.GetChildObject<Grid>(pan, "grd");
            Grid pro = Com.GetChildObject<Grid>(grd, "pro");
            Grid btns = Com.GetChildObject<Grid>(grd, "btns");
            Button btn = Com.GetChildObject<Button>(btns, "btn_Play");
            btn.Content = "播放";
        }

        public static RingViewModel getRingContent(Button btn)
        {
            Grid btns = Com.GetParentObject<Grid>(btn, "btns");
            Grid grd = Com.GetParentObject<Grid>(btns, "grd");
            StackPanel pan = Com.GetParentObject<StackPanel>(grd, "pan");
            ListBoxItem item = Com.GetParentObject<ListBoxItem>(pan, "");
            return item.Content as RingViewModel;
        }

    }
}
